package com.spark.laboratory.utils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Random;

public class JWTUtils {

    /**
     * 传入 xjwt密文
     * @param token xjwt密文
     * @return 结果json
     * @throws Exception 异常
     */
    public static String dencrty(String token) throws Exception {
        //获取当前时间
        long now = System.currentTimeMillis();
        //创建JWT实例
        JWT jwt = new JWT(KEY.secret, KEY.aeskey,now,KEY.issueId);
        //对数据进行url 解码
        token = URLDecoder.decode(token,"UTF-8");
        //解密数据
        return jwt.verifyAndDecrypt(token, now);
    }

    /**
     * json xjwt加密
     * @param json 提交的json
     * @return xjwt密文
     * @throws Exception 异常
     */
    public static String encrty(String json) throws Exception {
        // 获取当前时间
        long now = System.currentTimeMillis();
        // 创建JWT实例
        JWT jwt=new JWT(KEY.secret,KEY.aeskey,now,KEY.issueId);
        // 创建payload
        ByteBuffer payload = ByteBuffer.allocate(1024).order(ByteOrder.BIG_ENDIAN);
        payload.put(json.getBytes(StandardCharsets.UTF_8)).flip();
        // 创建out
        ByteBuffer out = ByteBuffer.allocate(1024);
        //加密数据 设置过期时间，例:10分钟
        jwt.encryptAndSign(JWT.Type.SYS,payload,out,now + 10*60*1000);
        String xjwt = new String(out.array(),out.arrayOffset(),out.remaining());
        // 对数据进行url 编码
        return URLEncoder.encode(xjwt,"UTF-8");
    }

    /**
     * 随机生成16位字符串
     * @return String
     */
    public static String getRandomString(){
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ;i < 16;i ++){
            if (i % 2 == 0) {
                char[] cha ={'A','B','C','D','E','F'};
                int i1 = (int) (Math.random() * (cha.length));
                sb.append(cha[i1]);
            }else {
                sb.append(new Random().nextInt(10));
            }
        }
        return sb.toString();
    }
}
